<?php

namespace Yi\Permission\Http\Controllers;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Illuminate\Support\Facades\Log;

use Yi\Permission\Support\Crypt\AES;

use Carbon;
use Yi\Permission\Models\User;
use Illuminate\Support\Facades\Auth;

use Yi\Permission\Models\Auth\Role;
use Yi\Permission\Models\Auth\Menu;


class AdminUserLoginController extends Controller
{
    //

    public $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function login()
    {
        $user = User::where('username', request('username'))->first();
        if ($user && Hash::check(request('password'), $user->password)) {
            $tokenResult = $user->createToken('backend');
            $accessToken = $tokenResult->accessToken;
            $data = [
                'access_token' => $accessToken,
                'token_type' => 'Bearer',
                'expires_at' => Carbon\Carbon::parse(
                    $tokenResult->token->expires_at
                )->toDateTimeString()
            ];
            return success($data);
        } else {
            return fail('4001', "登录失败");
        }
    }

    /**
     *  修改个人信息
     *
     * */
    public function setting()
    {
    }

    /**
     *  修改密码
     */
    public function passwordReset(Request $request)
    {
        $user = auth('backend')->user();
        $input = $request->only(['old_password', 'password', 'confirm_password', 'crypt_key']);

        Log::debug('passwordReset', [$input]);

        $input['old_password'] = AES::decodeRsa($input['crypt_key'], $input['old_password']);
        if (Hash::check($input['old_password'], $user->password)) {
            if ($input['password'] == $input['confirm_password']) {
                $input['password'] = AES::decodeRsa($input['crypt_key'], $input['password']);
                $user->update(['password' => $input['password']]);
                return success(["ok"]);
            }
        } else {
            return fail(5000, "原密码不正确");
        }
    }


    //获取用户信息
    public function currentUser(Request $request)
    {
        $user = auth('backend')->user();
        $user["haveAccessMenu"] = $this->getAuthMenu($user);
        return success($user);
    }

    public function logout()
    {
        // 验证访问令牌
        if (Auth::guard('backend')->check()) {
            // 注销当前用户
            Auth::guard('backend')->user()->token()->delete();
        }

        // auth()->guard('backend')->user()->token()->revoke();
        return success(["data" => 'logout success!']);
    }


    /***
     * 
     * 显示我的菜单 
     */
    function currentUserMenus()
    {
        $arrUserInfo = auth('backend')->user(); //获取用户信息
        $myMenuIds = [];
        // 非超管查询角色IDs
        if (!$arrUserInfo['is_super']) {
            $menuRows = Role::whereIn("id", $arrUserInfo['role_ids'])->pluck('menu_ids');
            Log::debug("myMenuIds__________1", [gettype($menuRows), $menuRows]);
            if ($menuRows) {
                foreach ($menuRows as $val) {
                    $myMenuIds = array_merge($myMenuIds, $val);
                }
            }
        }

        Log::debug("myMenuIds__________2", [gettype($myMenuIds), $myMenuIds]);
        //根据菜单id 
        $menusData = Menu::where(function ($query) use ($myMenuIds) {
            if (count($myMenuIds) > 0) {
                $query->whereIn("id", array_unique($myMenuIds));
            }
        })->select(["id", "parent_id", "name", "name_cn", "type", "icon", "path", "component", "visible", "sort"])
            ->whereIn("type", [1, 2])
            ->orderBy("sort", "asc")->get();
        foreach ($menusData as $key => $val) {
            $menusData[$key]['hideInMenu'] = !($val['visible']);
        }

        // 生成菜单树状结构
        $menus = getTree($menusData);

        return $menus;
    }

    /**
     * 返回所有的菜单
     */
    private function getAuthMenu($arrUserInfo)
    {
        $myMenuIds = [];
        // 非超管查询角色IDs
        if (!$arrUserInfo['is_super']) {
            $menuRows = Role::whereIn("id", $arrUserInfo['role_ids'])->pluck('menu_ids');
            if ($menuRows) {
                foreach ($menuRows as $val) {
                    $myMenuIds = array_merge($myMenuIds, $val);
                }
            }
        }

        //获取所有可以有权访问的菜单集合
        $haveMenuList = Menu::where(function ($query) use ($myMenuIds) {
            if (count($myMenuIds) > 0) {
                $query->whereIn("id", array_unique($myMenuIds));
            }
        })->pluck("name");
        return  $haveMenuList;
    }
}
